/**
 * Created with IntelliJ IDEA.
 * User: teddy zhang
 * Date: 2015-04-09
 * Time: 17:43
 */
define(function (require, exports, module) {
    'use strict';
    
    var rk = require('rk');
    
    var iconMap = require('core/utils/uploadUtil');
    require('../rescenterBaseCtrl');
    require('../detail/rescenterDetailCtrl');
    var rescenter = require('../global/rescenterGlobal');

    $.widget('rk.rescenterListCtrl', $.rk.rescenterBaseCtrl, {
        options: {
            groupId: null,
            directoryId: null,
            url: null,
            userId: SESSION.user.id,
            postProcessor: null,
            preProcessor: null
        },
        ajaxHandler: null,
        _create: function () {
            var me = this;
            var elem = me.element;
            var opt = me.options;

            me._bind();


        },


        _init: function () {
            var me = this;
            var elem = me.element;
            var opt = me.options;

            me._render();
            me.load();
        },

        setOptions: function (options) {
            var me = this;
            var elem = me.element;
            me._setOptions(options);
        },

        setOption: function (key, value) {
            var me = this;
            var elem = me.element;
            me._setOption(key, value);
        },


        _render: function () {
            var me = this;
            var elem = me.element;
            var opt = me.options;

            opt.groupId = me._getGroup().groupId || (window.console && console.error('groupId is missing.'));
            opt.directoryId = me._getDirectoryId() || (window.console && console.error('directoryId is missing.'));
            opt.url = me._getGroup().list_action || (window.console && console.error('url is missing.'));


            me._getListPanelContainer().html(rk.templateText(require('oa/tmpl/rescenter/tpl_rescenter_nav.tpl'), $.extend({}, opt, {name: rescenter.depart.name})));
            //
            var $nav_first = me._getNavContainer().find('li.first');
            $('#rescenter_department_select').singletreepicker({
                //nowrap:true,
                width: 50, //控件宽度
                height: 50, //控件高度
                clickSelector: me._getNavContainer().find('div.dep-list>a.arrow'),
                menuWidth: 250,
                source: '/json/crm_dimension/depart-tree.action?dimType=1',
                onSuccess: function (o) {
                    me.setOption('directoryId', $nav_first.attr('data-id'));
                    me.setOption('groupId', o.value);
                    $nav_first.find('>a').text(o.label);
                    me.load();
                    $nav_first.nextAll('li').remove();
                }
            });

        },


        load: function (container,callback) {
            var me = this,
                elem = me.element,
                opt = me.options;
            var $listContainer = container || me._getListContainer();
            me._trigger('preProcessor', null, null);
            $listContainer.beLoading();
            //$listContainer.html('加载中...');
            var groupId = opt.groupId || me._getGroup().groupId || (window.console && console.error('groupId is missing.'));
            var directoryId = opt.directoryId || me._getDirectoryId() || (window.console && console.error('directoryId is missing.'));
            var listUrl = opt.listUrl || me._getGroup().list_action || (window.console && console.error('url is missing.'));

            if (me.ajaxHandler) me.ajaxHandler.abort();
            me.ajaxHandler = rk.get(listUrl, {gId: groupId, pId: directoryId}, function (data) {
                if (data.status === 0) {
                    data = data.data;
                    me.setOption('directoryId', data.currentDirectoryId);
                    me.setOption('groupId', data.currentGroupId);
                    if ($.isEmptyObject(data.directories) && $.isEmptyObject(data.twitterFiles)) {
                        me._blank(rk.i18n('TWITTERFILE_DOC_EMPTY'));
                        return;
                    }
                    $.each(data.twitterFiles, function (idx, _tf) {
                        _tf.owner = data.users[_tf.userId].name;
                        me._assembleTplData(_tf);
                    });
                    //仁科互动租户定制(周培军可以删除所有文档)
                    data.session = SESSION;
                    $listContainer.html(rk.templateText(require('oa/tmpl/rescenter/tpl_rescenter_list.tpl'), data));
                    if(!$listContainer.isScroll())
                    $listContainer.unScroll(true).beScroll();
                }
            }).done(function (data) {
                callback && callback.call(me);
                me._trigger('postProcessor', null, data.data);
            });
        },

        _blank: function (text) {
            var me = this;
            var elem = me.element;

            var tpl = require('oa/tmpl/_default/blank-cup.tpl');
            var html = rk.templateText(tpl, {text: text});
            me._getListContainer().html(html);
        },


        _assembleTplData: function (_tf) {
            var me = this;
            var elem = me.element;
            _tf.timeLine = moment(parseFloat(_tf.updatedAt)).format('YYYY-MM-DD');
            var arr = _tf.fileName.split('.');
            var fileType = '.' + arr[arr.length - 1];
            _tf.fileType = iconMap.getIconClass(fileType);
            _tf.detailUrl = '/final/file.action?fid=' + _tf.id;
            _tf.downloadUrl = '/json/sns_twitter_file/' + 'download.action?fileId=' + _tf.id + '&checkCode=' + _tf.tfcode;
            return _tf;
        },


        _updateNav: function (_name, _id) {
            var me = this,
                elem = me.element,
                opt = me.options;
            var $parent_li = me._getNavContainer().find('li').last();
            //$parent_li.html('<a  href="javascript:void(0);">' + $parent_li.find('>a').html() + '</a>');
            var li_HTML = '<li data-name="' + _name + '" data-id="' + opt.directoryId + '">' + _name + '</li>';


            var isRoot = (me._getNavContainer().find('li').size() == 1);
            var isDepart = me._getNavContainer().find('div.dep-list').size();
            if (isRoot && !isDepart) {
                var $rootElem = me._getNavContainer().find('li.first');
                var lastName = $rootElem.attr('data-name');
                var lastId = $rootElem.attr('data-id');
                $rootElem.replaceWith('<li class="first" data-name="' + lastName + '" data-id="' + lastId + '" ><a  href="javascript:void(0);">' + lastName + '</a></li>');
            }

            me._getNavContainer().find('li').last().after(li_HTML);
            var nav_height = me._getNavContainer().height();
            var scroll_height = 'calc(100% - ' + nav_height + 'px)';
            me._getListContainer().css('height', scroll_height);


        },

        _bind: function () {
            var me = this;
            var elem = me.element;
            var opt = me.options;


            /** 目录事件 */
            me._getListPanelContainer().on('click', 'div[data-type="directory"]', function (event) {
                var $directory = $(this);
                me.setOption('directoryId', $directory.attr('data-id'));
                me.load(null,function(){
                    me._updateNav($directory.attr('data-name'));
                });


                return false;
            });


            /** 目录导航事件 */
            me._getListPanelContainer().on('click', 'li', function (event) {
                var $directory = $(this);
                var _id = $directory.attr('data-id');
                $directory.nextAll('li').remove();
                var isRoot = (Number(_id) === -1);
                var $rootElem = me._getNavContainer().find('li.first');
                var isDepart = $rootElem.find('div.dep-list').size();
                if (isRoot && !isDepart) {
                    var lastName = $rootElem.attr('data-name');
                    var lastId = $rootElem.attr('data-id');
                    $rootElem.replaceWith('<li class="first" data-name="' + lastName + '" data-id="' + lastId + '" > <span class="document_title_li">' + lastName + '</span></li>');
                }
                opt.directoryId = _id;
                me.load();
            });
            /** 文档删除-*/
            me._getListPanelContainer().on('click', 'a.file_delete', function (event) {
                var $lnk = $(this);
                if ($lnk.hasClass('file_delete')) {
                    event.preventDefault();
                    var $lnk = $(this);
                    rk.confirm(rk.i18n('TWITTERFILE_DOC_DELETED_CONFIRM'), function () {
                        $.postJson('/json/sns_twitter_file/delete.action', {
                            fileId: $lnk.attr('data-id')
                        }).done(function (json) {
                            if (json.status == 0) {
                                rk.noticeSuccess(rk.i18n('TWITTERFILE_DOC_DELETED_SUCCESSFUL'));
                                $lnk.parents('div.show-content').remove();
                                rk.oa.closeContent();
                            } else {
                                rk.noticeError(rk.i18n('TWITTERFILE_DOC_DELETED_FAILURE'));
                            }
                        }).fail(function (def, code, message) {
                            def.status != 0 && rk.noticeError(rk.i18n('REQUEST_ERROR'));
                        });
                    });
                    return false;
                }
            });


            /** 文档收藏事件-*/
            me._getListPanelContainer().on('click', '.res_opration_area>span', function (event) {
                var $_a = $(this).find('>a');
                var _style = $_a.hasClass('file_uncollect') ? 'file_collect' : 'file_uncollect';
                var favor = (_style == 'file_uncollect');
                var fid = $_a.attr('data-id');
                if (favor) {
                    rk.confirm(rk.i18n('TWITTERFILE_CANCEL_FAVORITES_CONFIRM'), function () {
                        $.postJson('/json/sns_twitter_file_fav/cancel.action', {
                            sid: fid
                        }).done(function (json) {
                            if (json.status == 0) {
                                rk.noticeSuccess(rk.i18n('TWITTERFILE_CANCEL_FAVORITES_SUCCESSFUL'));
                                $_a.removeClass().addClass(_style);
                            } else {
                                rk.noticeError(rk.i18n('TWITTERFILE_CANCEL_FAVORITES_FAILURE'));
                            }
                        }).fail(function (def, code, message) {
                            def.status != 0 && rk.noticeError(rk.i18n('REQUEST_ERROR'));
                        });
                    });
                } else {
                    $.postJson('/json/sns_twitter_file_fav/save.action', {
                        sid: fid
                    }).done(function (json) {
                        if (json.status == 0) {
                            rk.noticeSuccess(rk.i18n('TWITTERFILE_ADD_FAVORITES_SUCCESSFUL'))
                            $_a.removeClass().addClass(_style);
                        } else {
                            rk.noticeError(rk.i18n('TWITTERFILE_ADD_FAVORITES_FAILURE'));
                        }
                    }).fail(function (def, code, message) {
                        def.status != 0 && rk.noticeError(rk.i18n('REQUEST_ERROR'));
                    });
                }

                return false;
            });


            /** 文档下载事件*/
            me._getListPanelContainer().on('click', 'a.file_download', function (event) {
                event.preventDefault();
                window.location.href = event.target.href;
                return false;
            });

            /** 文档详情页*/

            me._getListPanelContainer().on('click', 'div.show-content[data-type="file"]', function (event) {
                event.preventDefault();
                var $this = $(this);
                if(!$this.hasClass("show-content-hover")){
                    $this.addClass("show-content-hover");
                }
                $this.siblings().removeClass("show-content-hover");


                rk.oa.popupContent({
                    size: 'middle',
                    onSuccess: function (contentElem) {
                        contentElem.fileDetail({selector: $this});
                    }
                });
                return false;
            });


            /** 文档移动事件*/
            me._getListPanelContainer().moveDoc({
                groupID: function () {
                    return opt.groupId;
                },
                selector: 'a.file_move',
                fidName: 'data-id',
                listUrl: function () {
                    return me._getGroup().list_dic;
                },
                moveUrl: function () {
                    return me._getGroup().move_dic;
                },
                success: function () {
                    me.getPanel().rescenterListCtrl('load');
                }
            });


        }


    });
});
